package com.yb.app_trend;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.yb.app_trend.model.TrendModel;
import com.yb.app_trend.model.TrendModelVo;
import com.yb.app_trend.util.DensityUtil;

import org.jsoup.Jsoup;
import org.jsoup.nodes.DataNode;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    Handler handler;


    TextView time;


    TableLayout table;


    private List<TrendModel> trendModels;

    Gson gson=new Gson();

    public SharedPreferences getSharedPreferences() {
        return   getApplicationContext().getSharedPreferences("map", Context.MODE_PRIVATE);
    }

    public TrendModelVo getValue(String key){
        SharedPreferences sharedPreferences = getSharedPreferences();
        String result = sharedPreferences.getString(key, "");

        Log.d("result",result);
        TrendModelVo trendModelVo=null;

        if(result!=null&&result!=""){
            trendModelVo=gson.fromJson(result, TrendModelVo.class);
        }

        return trendModelVo;

    }



    private void setT1(String key,String t1){
        TrendModelVo exists = getValue(key);


        if(exists==null){
            exists=new TrendModelVo()   ;
        }
        exists.setT1(t1);

        setValue(key,exists);

    }

    private void setT2(String key,String t2){
        TrendModelVo exists = getValue(key);

        if(exists==null){
            exists=new TrendModelVo()   ;
        }
        exists.setT2(t2);

        setValue(key,exists);

    }




    private void setT3(String key,String t3){
        TrendModelVo exists = getValue(key);
        if(exists==null){
            exists=new TrendModelVo()   ;
        }
        exists.setT3(t3);

        setValue(key,exists);

    }

    private void setT4(String key,String t4){

        TrendModelVo exists = getValue(key);

        if(exists==null){
            exists=new TrendModelVo()   ;
        }
        exists.setT4(t4);

        setValue(key,exists);

    }
    public void setValue(String key,TrendModelVo trendModelVo){

        try {
            SharedPreferences.Editor edit = getSharedPreferences().edit();

            edit.putString(key,gson.toJson(trendModelVo));

            edit.apply();

            Log.d("apply=>","success");
        }catch (Exception e){
            Log.d("ex=>",e.toString());
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        time = findViewById(R.id.time);
        table = findViewById(R.id.table);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String timeStr = dateTimeFormatter.format(LocalDateTime.now());
        time.setText(timeStr);
        handler=new Handler(msg -> {

            fillTable();
            return true;
        });

        new Thread(() -> {

            Request request = new Request.Builder().url("http://cz89.com/kaijiang/3d/sjh").build();
            OkHttpClient client = new OkHttpClient();

            Call call = client.newCall(request);
            try {
                Response response = call.execute();
                String result = response.body().string();
                parseResult(result);
            } catch (IOException e) {
                Log.d("e=>",e.toString());
            }

        }).start();

    }


    private void parseResult(String domString){

        Document document = Jsoup.parse(domString);

        Element element = document.selectFirst("table.kjTable tbody");


        trendModels=new ArrayList<>();


        Elements trs = element.select("tr");

        trs.forEach(tr->{

            Elements tds = tr.select("td");


            Element td0 = tds.get(0);
            Element td1 = tds.get(1);
            Element td2 = tds.get(2);
            Element td3 = tds.get(3);
            Element td4 = tds.get(4);

            TrendModel trendModel = new TrendModel();
            trendModel.setIssueNo(td0.text());
            trendModel.setOn(td1.text());
            trendModel.setTryon(td2.text());
            trendModel.setNo(td3.text());
            trendModel.setSameNo(td4.text());

            TrendModelVo trendModelVo = getValue(td0.text());


            Log.d("trendModelVo=>",trendModelVo!=null?trendModelVo.toString():"");
            if(trendModelVo!=null){
                trendModel.setT1(trendModelVo.getT1());
                trendModel.setT2(trendModelVo.getT2());
                trendModel.setT3(trendModelVo.getT3());
                trendModel.setT4(trendModelVo.getT4());
            }

            trendModels.add(trendModel);


        });
        Message message = Message.obtain();
        handler.sendMessage(message);
    }


    private void fillTable(){

        Log.e("fillTable=>",trendModels.toString());
        table.removeAllViews();

        TableRow headerRow = new TableRow(getApplicationContext());

        table.addView(headerRow);

        headerRow.setBackgroundResource(R.color.white);
        ViewGroup.MarginLayoutParams _layoutParams =(ViewGroup.MarginLayoutParams) headerRow.getLayoutParams();
        int margin = DensityUtil.dip2px(getApplicationContext(), 1);
        _layoutParams.setMargins(margin,margin,margin,margin);

        TextView header_issueNo = new TextView(getApplicationContext());
        header_issueNo.setGravity(Gravity.CENTER);
        header_issueNo.setText("期数");
        TextView header_on = new TextView(getApplicationContext());
        header_on.setGravity(Gravity.CENTER);

        header_on.setText("开机");
        TextView header_tryon = new TextView(getApplicationContext());
        header_tryon.setGravity(Gravity.CENTER);

        header_tryon.setText("试机");
        TextView header_no = new TextView(getApplicationContext());
        header_no.setGravity(Gravity.CENTER);

        header_no.setText("奖号");
        TextView header_sameNo = new TextView(getApplicationContext());
        header_sameNo.setGravity(Gravity.CENTER);

        header_sameNo.setText("同号");

        TextView t1 = new TextView(getApplicationContext());
        t1.setGravity(Gravity.CENTER);
        t1.setText("试机");
        TextView t2 = new TextView(getApplicationContext());
        t2.setGravity(Gravity.CENTER);

        t2.setText("奖号");

        TextView t3 = new TextView(getApplicationContext());
        t3.setGravity(Gravity.CENTER);
        t3.setText("试机");

        TextView t4 = new TextView(getApplicationContext());
        t4.setGravity(Gravity.CENTER);
        t4.setText("奖号");

        headerRow.addView(header_issueNo);
        headerRow.addView(header_on);
        headerRow.addView(header_tryon);
        headerRow.addView(header_no);
        headerRow.addView(header_sameNo);
        headerRow.addView(t1);
        headerRow.addView(t2);
        headerRow.addView(t3);
        headerRow.addView(t4);


        int textSize=DensityUtil.dip2px(getApplicationContext(), 5);

        // 添加表头
        trendModels.forEach(trendModel -> {




            TableRow tableRow = new TableRow(getApplicationContext());

            table.addView(tableRow);

            tableRow.setBackgroundResource(R.color.white);
            ViewGroup.MarginLayoutParams layoutParams =(ViewGroup.MarginLayoutParams) tableRow.getLayoutParams();

            layoutParams.leftMargin= margin;
            layoutParams.rightMargin= margin;
            layoutParams.bottomMargin= margin;

            TextView issueNo = new TextView(getApplicationContext());
            issueNo.setGravity(Gravity.CENTER);
            issueNo.setText(trendModel.getIssueNo());
            TextView on = new TextView(getApplicationContext());
            on.setGravity(Gravity.CENTER);

            on.setText(trendModel.getOn());
            TextView tryon = new TextView(getApplicationContext());
            tryon.setGravity(Gravity.CENTER);

            tryon.setText(trendModel.getTryon());
            TextView no = new TextView(getApplicationContext());
            no.setGravity(Gravity.CENTER);

            no.setText(trendModel.getNo());
            TextView sameNo = new TextView(getApplicationContext());
            sameNo.setGravity(Gravity.CENTER);

            sameNo.setText(trendModel.getSameNo());

            EditText textView1 = new EditText(getApplicationContext());
            textView1.setGravity(Gravity.CENTER);
            textView1.setTextSize(textSize);
            textView1.setText(trendModel.getT1());
            textView1.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    setT1(trendModel.getIssueNo(),s.toString());

                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });

            EditText textView2 = new EditText(getApplicationContext());
            textView2.setGravity(Gravity.CENTER);
            textView2.setText(trendModel.getT2());
            textView2.setTextSize(textSize);
            textView2.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    setT2(trendModel.getIssueNo(),s.toString());
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });

            EditText textView3 = new EditText(getApplicationContext());
            textView3.setGravity(Gravity.CENTER);
            textView3.setTextSize(textSize);
            textView3.setText(trendModel.getT3());
            textView3.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    setT3(trendModel.getIssueNo(),s.toString());
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
            EditText textView4 = new EditText(getApplicationContext());
            textView4.setGravity(Gravity.CENTER);
            textView4.setTextSize(textSize);

            textView4.setText(trendModel.getT4());
            textView4.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    setT4(trendModel.getIssueNo(),s.toString());
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
            tableRow.addView(issueNo);
            tableRow.addView(on);
            tableRow.addView(tryon);
            tableRow.addView(no);
            tableRow.addView(sameNo);
            tableRow.addView(textView1);
            tableRow.addView(textView2);
            tableRow.addView(textView3);
            tableRow.addView(textView4);


        });
    }



}
